package com.example.joblinker.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.joblinker.common.Result;
import com.example.joblinker.dto.LoginDTO;
import com.example.joblinker.dto.RegisterDTO;
import com.example.joblinker.entity.User;
import com.example.joblinker.mapper.UserMapper;
import com.example.joblinker.service.UserService;
import com.example.joblinker.util.JwtUtil;
import com.example.joblinker.vo.UserVO;
import lombok.Data;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * 用户控制器
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private UserService userService;

    @Resource
    private UserMapper userMapper;

    @Resource
    private JwtUtil jwtUtil;

    /**
     * 用户注册
     *
     * @param registerDTO 注册信息
     * @return 注册结果
     */
    @PostMapping("/register")
    public Result<UserVO> register(@Validated @RequestBody RegisterDTO registerDTO) {
        try {
            UserVO userVO = userService.register(registerDTO);
            return Result.success(userVO);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    /**
     * 用户登录
     *
     * @param loginDTO 登录信息
     * @return 登录结果
     */
    @PostMapping("/login")
    public Result<UserVO> login(@Validated @RequestBody LoginDTO loginDTO) {
        try {
            UserVO userVO = userService.login(loginDTO);
            return Result.success(userVO);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    /**
     * 获取当前用户信息
     *
     * @param request HTTP请求
     * @return 用户信息
     */
    @GetMapping("/profile")
    public Result<UserVO> getCurrentUser(HttpServletRequest request) {
        try {
            UserVO userVO = userService.getCurrentUser(request);
            return Result.success(userVO);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    /**
     * 获取用户列表
     *
     * @param page 页码
     * @param size 每页大小
     * @param keyword 搜索关键词
     * @return 用户列表
     */
    @GetMapping("/list")
    public Result<Page<UserVO>> getUserList(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) String keyword) {
        try {
            Page<UserVO> userList = userService.getUserList(page, size, keyword);
            return Result.success(userList);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    /**
     * 更新用户状态
     *
     * @param id 用户ID
     * @param statusWrapper 状态包装对象
     * @return 更新结果
     */
    @PutMapping("/{id}/status")
    public Result<Void> updateUserStatus(
            @PathVariable Long id,
            @RequestBody StatusWrapper statusWrapper) {
        try {
            System.out.println("接收到的ID: " + id);
            System.out.println("接收到的状态包装对象: " + statusWrapper);
            if (statusWrapper == null || statusWrapper.getStatus() == null) {
                return Result.error("状态不能为空");
            }
            userService.updateUserStatus(id, statusWrapper.getStatus());
            return Result.success();
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    /**
     * 状态包装类
     */
    @Data
    public static class StatusWrapper {
        private Integer status;
    }

    /**
     * 重置用户密码
     *
     * @param id 用户ID
     * @return 重置结果
     */
    @PostMapping("/{id}/password/reset")
    public Result<Void> resetUserPassword(@PathVariable Long id) {
        try {
            userService.resetUserPassword(id);
            return Result.success();
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    /**
     * 更新用户信息
     *
     * @param id 用户ID
     * @param userVO 用户信息
     * @return 更新结果
     */
    @PutMapping("/{id}")
    public Result<Void> updateUser(
            @PathVariable Long id,
            @RequestBody UserVO userVO) {
        try {
            userVO.setId(id);
            userService.updateUser(userVO);
            return Result.success();
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    /**
     * 删除用户
     *
     * @param id 用户ID
     * @return 删除结果
     */
    @DeleteMapping("/{id}")
    public Result<Void> deleteUser(@PathVariable Long id) {
        try {
            userService.deleteUser(id);
            return Result.success();
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    /**
     * 检查用户是否已关联公司信息（针对招聘者）
     */
    @GetMapping("/check-company")
    public Result<Map<String, Object>> checkCompanyInfo(HttpServletRequest request) {
        Long userId = jwtUtil.getUserIdFromRequest(request);
        User user = userMapper.selectById(userId);
        
        if (user == null) {
            return Result.error("用户不存在");
        }
        
        Map<String, Object> result = new HashMap<>();
        
        // 如果不是招聘者，返回不需要关联公司
        if (user.getRole() != 1) {
            result.put("needCompany", false);
            return Result.success(result);
        }
        
        // 检查是否已关联公司
        boolean hasCompany = user.getCompanyId() != null && user.getCompanyId() > 0;
        result.put("needCompany", !hasCompany);
        
        // 无论是否有关联公司，都返回 companyId 字段
        // 如果没有关联公司，返回 null 或 0
        result.put("companyId", user.getCompanyId());
        
        return Result.success(result);
    }
    
    /**
     * 上传用户头像
     *
     * @param file 头像文件
     * @param request HTTP请求
     * @return 上传结果
     */
    @PostMapping("/avatar")
    public Result<Map<String, String>> uploadAvatar(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
        try {
            if (file.isEmpty()) {
                return Result.error("上传的文件不能为空");
            }
            
            // 获取当前用户ID
            Long userId = jwtUtil.getUserIdFromRequest(request);
            if (userId == null) {
                return Result.error("未登录或登录已过期");
            }
            
            // 获取文件名和扩展名
            String originalFilename = file.getOriginalFilename();
            if (originalFilename == null) {
                return Result.error("无法获取文件名");
            }
            
            String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
            if (!extension.equalsIgnoreCase(".jpg") && !extension.equalsIgnoreCase(".jpeg") && !extension.equalsIgnoreCase(".png")) {
                return Result.error("只支持JPG或PNG格式的图片");
            }
            
            // 生成新的文件名
            String newFilename = UUID.randomUUID().toString() + extension;
            
            // 确保上传目录存在
            String uploadDir = "uploads/avatars";
            File dir = new File(uploadDir);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            
            // 保存文件
            Path path = Paths.get(uploadDir, newFilename);
            Files.write(path, file.getBytes());
            
            // 更新用户头像信息
            User user = userMapper.selectById(userId);
            if (user != null) {
                user.setAvatar("/uploads/avatars/" + newFilename);
                userMapper.updateById(user);
            }
            
            // 返回头像URL
            Map<String, String> result = new HashMap<>();
            result.put("url", "/uploads/avatars/" + newFilename);
            
            return Result.success(result);
        } catch (IOException e) {
            e.printStackTrace();
            return Result.error("头像上传失败: " + e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("头像上传失败: " + e.getMessage());
        }
    }
} 